package com.xsq;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;

import com.common.utils.LogUtils;
import com.xsq.util.HttpInterface;

@SuppressLint("SimpleDateFormat")
public class MyTimeTask {

	private static HttpInterface httpInterface;
	
	private static String posno;
	
	private static Map<String,Object> otherInfo;
	
	private static  Timer timer = new Timer();
	
	private static boolean doing = false;
	
	private static MyTimeTask instance;
	
	public  SharedPreferences preferences;
	public  SharedPreferences.Editor editor;
	
	public static MyTimeTask getInstance(HttpInterface hi,String p_posno,Map<String,Object> p_otherInfo) {
		if (instance == null) {
			instance = new MyTimeTask(hi, p_posno, p_otherInfo);
		}else{
			posno = p_posno;
			otherInfo = p_otherInfo;
		}
		return instance;
	}

	public MyTimeTask(HttpInterface hi,String p_posno,Map<String,Object> p_otherInfo) {
		httpInterface = hi;
		posno = p_posno;
		otherInfo = p_otherInfo;
	}
	
	
	public  void startupTask() {
		
		doing = true;

		TimerTask task = new TimerTask() {

			@Override
			public void run() {

				try {
					
					String curTime = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
					// 执行心跳
					
					Map<String,Object> result = httpInterface.refreshPosLink(posno, curTime, otherInfo);
					
					LogUtils.info(Thread.currentThread().getName()+" 发送心跳-->"+posno+"  -->"+curTime+"-->"+otherInfo+" 返回-->"+result);
					
					if(String.valueOf(result.get("is_success")).equals("1")){
						//成功,则更新次消费限额
						
						String xfxx = String.valueOf(result.get("xfxe"));
						if(preferences.getString(Constant.CACHE_XFXX, "0").equals(xfxx)){
							LogUtils.info("次消费限额无变化,为"+xfxx);
						}else{
							editor.putString(Constant.CACHE_XFXX, xfxx);
							editor.commit();
							
							LogUtils.info("----消费限额修改,为"+xfxx);
						}
						
					}else if(String.valueOf(result.get("is_success")).equals("0")){
						//失败,非网络失败
						if(String.valueOf(result.get("error_code")).equals("0")){
							//设备号已经不存在的问题
							
						}else if(String.valueOf(result.get("error_code")).equals("1")){
							//后台异常,暂不处理
						}
					}else{
						//网络异常,暂不处理
					}
					
				} catch (Exception e) {

				}

			}
		};

		timer.schedule(task, 10*1000, 60 * 1000);
		
		LogUtils.info(Thread.currentThread().getName()+"  开启任务了啊...............");
	}
	
	
	public void cancelTask(){
		doing = false;
		if(timer != null ){
			timer.cancel();
		}
	}

	public  boolean isDoing() {
		return doing;
	}

	

	
	
}
